package com.db.onlinedb.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 连接封装
 */
public class Conn {
    private Connection connection = null;

    /**
     * 连接数据库，并且返回Connection
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     * @return Connection
     */
    public Connection getConnection(String host, String port, String username, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("com.mysql.jdbc.Driver not found!");
        }
        try {
            connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/mysql?characterEncoding=UTF-8", username, password);
            System.out.println("数据库连接成功!");
        } catch (SQLException e) {
            System.out.println("数据库连接失败!");
        }
        return connection;
    }
    public Connection requestConnection(){
        if(this.connection==null)
            return null;
        else
            return this.connection;
    }
}
